package com.zx.mes.redis.hyl.service.impl;

import com.zx.mes.redis.hyl.service.RedisCacheWeatherI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 实现接口RedisCacheWeatherI
 * 由key值从redis中获取对应数据,key为String类型(如是其它类型,需重新实现)
 * 获得的值以json字符串返回
 * @author hyl
 * @date 2018-3-2
 */
@Service
public class RedisCacheWeatherImpl implements RedisCacheWeatherI {

    public static final int TIMEOUT = 180;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(RedisCacheWeatherImpl.class);


    @Override
    public void setCache(String key, String jsonStr) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(key,jsonStr, (long) (TIMEOUT+Math.abs(Math.random()*100)),TimeUnit.SECONDS);

        logger.info("setCache 存储缓存成功 参数key:{" + key +"},jsonStr:{" + jsonStr + "}");
    }

    @Override
    public String getCache(String key) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String result="hyl";
        // 先查缓存，缓存有的取缓存中的数据
        if (stringRedisTemplate.hasKey(key)) {
            result = ops.get(key);
            logger.info("getCache 获取缓存成功 参数key:{" + key +"},result:{" + result + "}");
        } else {
            logger.info("getCache 获取缓存失败 参数key:{" + key +"},result:{" + result + "}");
        }
        return result;
    }
}
